<?php
class Vs_Mapper
	
{
    public function save( $entity )
	{
		$table= $this->getTable();
		
		if ( ! $entity->getId() ){	
			return $entity->setId = $table->insert( $entity );
		} else {					
			return $table->update( $entity );	
		}	
	}
	
	public function delete( $entity )
    {
		$table= $this->getTable();
		return $table->delete( $entity );
	}
	
    public function getIdentityMap()
	{
		return My_IdentityMap::getInstance();
	}
	
	public function getTable( $name = null )
	{
	    if ($name){
	        return Vs_Factory::table($name);
	    } 
	    
		return Vs_Factory::table($this);
	}	
	
	public function getById( $id )
	{
		$rowset = $this->getTable()->find( $id );
		return $this->_fetch( $rowset->current() );
	}
	
	public function getByIds( $ids )
	{
		return $this->_fetchCollection( 
			$this->getTable()->getByIds( $ids )
		);
	}
	
	protected function _fetchCollection( $rowset, $name = null )
	{
	    if ($name == null){
	        $name = $this;
	    }
	    
		$collection = Vs_Factory::collection( $name );
		
		foreach ( $rowset as $row){
			$collection->append(
				$this->_fetch( $row )
			);
		}
		
		return $collection;
	}
	
	/**
	 * @param array
	 * @return object Ws_Entity
	 */
	protected function _fetch( $row, $name = null )
	{
	    if ($name == null){
	        $name = $this;
	    }
		
		return Vs_Factory::entity($name, $row);
	}
	
	
	/**
	 * @param array $params
	 * @param int $offset
	 * @param int $limit
	 * @param string $order
	 * @return Vs_Collection
	 */
	public function getByParams( $params = array(), $offset = null, $limit = null, $order = null ){
		
		$table= $this->getTable();
		
		return $this->_fetchCollection(
			$table->getByParams($params, $offset, $limit, $order)
		);
	}
	
	public function countByParams( $params ){
		return $this->getTable()->countByParams($params);
	}
	
	
}
